﻿using AutoMapper;

using CodeCarvings.Piczard.Web;

using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;

using ZFB.Common;
using ZFB.DTO;
using ZFB.IServices;
using ZFB.Models;
using ZFB.Models.EntityConfig;
using ZFB.Repository.Attachments;
using ZFB.Repository.House;

namespace ZFB.Services
{
    public class HouseServices : IHouseServices
    {
        private readonly IHouseRepository houseRepository;
        private readonly IAttachmentsRepository attachmentsRepository;
        private readonly MyDbContext db;
        
        private readonly IMapper mapper;
        public HouseServices(IHouseRepository houseRepository, IMapper mapper, IAttachmentsRepository attachmentsRepository, MyDbContext db)
        {
            this.houseRepository = houseRepository;
            this.mapper = mapper;
            this.attachmentsRepository = attachmentsRepository;
            this.db = db;
        }
        public async Task<ApiResult> AddNewAsync(AddHouseDTO addhouseDTO)
        { 
            var house = mapper.Map<T_Houses>(addhouseDTO);
            foreach (var item in addhouseDTO.AttachmentIds)
            {
                var attachments = await attachmentsRepository.GetModelAsync(e => e.Id == item);
                house.T_Attachments.Add(attachments);
            }
            var res= await  houseRepository.AddAsync(house);
            return res <= 0 ? new ApiResult("添加失败") : new ApiResult();
        }

        public async Task<ApiResult> AddPicsAsync(HousePicDTO housePicDTO)
        {
            var housePic = new T_HousePics
            {
                ThumbUrl = housePicDTO.ThumbUrl,
                Url = housePicDTO.Url,
                HouseId = housePicDTO.HouseId,
            };
            await db.T_HousePics.AddAsync(housePic);
            if (db.SaveChanges()>=1) return new ApiResult();
            return new ApiResult("添加失败");
        }

        public async Task<ApiResult> DeletePicAsync(long housePicId)
        {
            
                var pic = await db.T_HousePics.SingleOrDefaultAsync(e => e.Id == housePicId && !e.IsDeleted);
                if (pic == null)
                    return new ApiResult("图片不存在");
                pic.IsDeleted = true;
                if (db.SaveChanges() >= 1)
                    return new ApiResult();
                return new ApiResult("删除失败");
            
        }

        public async Task<ApiResult> GetAttachmentsAsync(long houseId)
        {
                var data = await houseRepository.GetListAsync(e => e.Id == houseId);
                if (data.IsNullOrEmpty())
                {
                    return new ApiResult("获取失败!");
                }
                else
                {
                   var atta = data.Single().T_Attachments;
                    var dto = mapper.Map<List<AttachmentDTO>>(atta);
                    return new ApiResult(dto);
                }
        }

        public async Task<ApiResult> GetByIdAsync(long id)
        {
           var data = await houseRepository.GetListAsync(e => e.Id == id);
            if (data.IsNullOrEmpty()) return new ApiResult("查询的不存在");
            var dto= mapper.Map<List<HouseDTO>>(data);
            return new(dto);
        }

        public async Task<ApiResult> GetCountAsync(long cityId, DateTime startDateTime, DateTime endDateTime)
        {
            var count =await houseRepository.LongCountAsync(e => e.T_Communities.T_Regions.CityId == cityId && e.CreateDateTime >= startDateTime && e.CreateDateTime <= endDateTime);
            return new ApiResult(count);
        }

        public async Task<ApiResult> GetPageDateAsync(long cityId, long typeId, int page, int limit)
        {
            var data= await houseRepository.GetPagesAsync(page, limit, e => e.T_Communities.T_Regions.CityId == cityId && e.TypeId == typeId);
            if (data == null) return new ApiResult("获取失败");
            var dto = mapper.Map<List<HouseDTO>>(data.Items);
            var pagedata = new Repository.Extensions.Page<HouseDTO>();
            pagedata.Items = dto;
            pagedata.TotalItems = data.TotalItems;
            pagedata.TotalPages = data.TotalPages;
            pagedata.ItemsPerPage = data.ItemsPerPage;
            pagedata.ItemsPerPage = limit;
            pagedata.CurrentPage = page;
            return new ApiResult(pagedata);
        }

        public async Task<ApiResult> GetPicsAsync(long houseId)
        {
           var data=await db.T_HousePics.Where(e => e.HouseId == houseId).AsNoTracking().ToListAsync();
            if (data.IsNullOrEmpty()) return new ApiResult("获取失败!");
            var dto = mapper.Map<List<HousePicDTO>>(data);
            return new ApiResult(dto);
        }

        public async Task<ApiResult> GetTotalCountAsync(long cityId, long typeId)
        {
            var count = await houseRepository.LongCountAsync(e => e.T_Communities.T_Regions.CityId == cityId &&e.TypeId==typeId);
            return new ApiResult(count);
        }

        public async Task<ApiResult> MarkDeleteAsync(long id)
        {
            if (!await houseRepository.IsExistAsync(e => e.Id == id))
                return new ApiResult("要删除的房子不存在!");
          var res=  await houseRepository.UpdateIsDeleteAsync(e => e.Id == id);
            return res <= 0 ? new ApiResult("删除失败") : new ApiResult();

        }

        public Task<ApiResult> SearchAsync(HouseSearchOptions houseSearchOptions)
        {
            throw new NotImplementedException();
        }

        public async Task<ApiResult> UpdateAsync(EditHouseDTO editDtO)
        {
          var data= await  houseRepository.GetModelAsync(e => e.Id == editDtO.id);
            if (data == null) return new("房屋不存在");
          var dto=mapper.Map<T_Houses>(data);
            data.T_Attachments.Clear();
            foreach (var item in editDtO.AttachmentIds) 
            {
                var attachments = await attachmentsRepository.GetModelAsync(e => e.Id == item);
               data.T_Attachments.Add(attachments);
            }
           var res= await  houseRepository.UpdateAsync(data);
            return res <= 0 ? new ApiResult("修改失败") : new ApiResult();
        }
    }
}
